/**
 * 日期弹窗：展示区回显及弹窗内回显
 * @params propItem
 * @returns object
 */
import moment from 'moment';
import { formatTime } from '@/utils';

export default {
  props: {
    propItem: Object,
  },
  data() {
    return {
      minDate: new Date(1950, 0, 1),
      maxDate: new Date(),
      current: new Date(),
      showPicker: false,
      innerValue: '',
      ...this.propItem,
    };
  },
  watch: {
    // 身份证号回显性别和出生日期
    'propItem.value': {
      handler(newValue) {
        this.innerValue = newValue;
        this.current = moment(newValue).toDate();
        this.onConfirm(newValue);
      },
      deep: true,
    },
  },
  mounted() {
    const { value, minDate, maxDate, current } = this;
    this.innerValue = value;
    this.minDate = minDate;
    this.maxDate = maxDate;
    this.current = current;
    if (value) {
      this.current = moment(value).toDate();
    }
  },
  methods: {
    onConfirm(value) {
      this.innerValue = formatTime(value);
      this.$emit('accept', { value: this.innerValue, code: this.code });
      this.showPicker = false;
    },
  },
  render() {
    return (
      <div>
        <van-field
          readonly
          clickable
          is-link
          value={this.innerValue}
          label={this.label}
          placeholder={this.placeholder}
          onClick={() => (this.showPicker = true)}
          rules={this.rules}
        />
        <van-popup v-model={this.showPicker} position="bottom">
          <van-datetime-picker
            v-model={this.current}
            type="date"
            title="选择年月日"
            min-date={this.minDate}
            max-date={this.maxDate}
            onConfirm={this.onConfirm}
            onCancel={() => (this.showPicker = false)}
          />
        </van-popup>
      </div>
    );
  },
};
